<template>
  <div class="query-settings-panel">
    <AxiomTitle title="查询参数设置" type="component" description="配置知识库查询的各项参数" />
    <AxiomForm ref="formRef" :model="formState" label-position="top" class="mt-4">
      <AxiomFormItem label="知识库" prop="kb_ids">
        <AxiomSelect
          v-model="formState.kb_ids"
          placeholder="请选择要查询的知识库"
          :options="knowledgeBaseOptions"
          multiple
          filterable
          collapse-tags
          collapse-tags-tooltip
          block
        />
      </AxiomFormItem>

      <AxiomFormItem label="知识库查询预设" prop="query_preset">
        <AxiomGroup class="w-full">
          <AxiomSelect
            v-model="selectedPresetId"
            placeholder="加载知识库预设"
            :options="queryPresetOptions"
            :disabled="!formState.kb_ids.length"
            clearable
            block
            @change="applyKnowledgePreset"
          >
            <template #option="{ option }">
              <AxiomGroup justify="space-between" align="center" class="w-full">
                <span>{{ option.label }}</span>
                <AxiomIcon v-if="option.is_default" name="StarFilled" style="color: var(--axiom-color-warning);" />
              </AxiomGroup>
            </template>
          </AxiomSelect>
          <AxiomTooltip content="将当前选中的预设设为默认">
            <AxiomButton icon="StarFilled" :disabled="isSetDefaultDisabled" @click="handleSetDefaultPreset" />
          </AxiomTooltip>
          <AxiomTooltip content="删除当前选中的预设">
            <AxiomButton icon="Delete" :disabled="!selectedPresetId" @click="handleDeletePreset" />
          </AxiomTooltip>
        </AxiomGroup>
      </AxiomFormItem>

      <AxiomFormItem label="全局查询策略" prop="preset_strategy">
        <AxiomSelect
          v-model="selectedStrategy"
          placeholder="加载一个全局策略覆盖当前配置"
          :options="presetStrategyOptions"
          clearable
          block
          @change="applyGlobalStrategy"
        />
      </AxiomFormItem>
      
      <AxiomGroup justify="end" class="mb-4" gap="small">
        <AxiomButton type="primary" :disabled="!selectedPresetId" @click="handleUpdatePreset">
          更新选中预设
        </AxiomButton>
        <AxiomButton type="primary" :disabled="!formState.kb_ids.length" @click="savePresetDialogVisible = true">
          保存为新预设
        </AxiomButton>
      </AxiomGroup>

      <AxiomDivider content-position="left">参数微调</AxiomDivider>

      <AxiomFormItem label="查询模式 (query_mode)" prop="query_mode">
        <AxiomRadioGroup v-model="formState.query_mode" :options="queryModeOptions" />
      </AxiomFormItem>

      <AxiomFormItem label="检索数量 (similarity_top_k)" prop="similarity_top_k">
        <AxiomInputSlider v-model="formState.similarity_top_k" :min="1" :max="50" />
      </AxiomFormItem>
      
      <AxiomFormItem label="上下文窗口 (context_window)" prop="context_window">
        <AxiomInputSlider v-model="formState.context_window" :min="0" :max="10" />
      </AxiomFormItem>

      <AxiomFormItem prop="rerank_score_threshold">
        <template #label>
          <AxiomGroup align="center" gap="small">
            <span>重排分数阈值</span>
            <AxiomTooltip content="仅保留分数高于此阈值的节点进行重排" placement="top">
              <AxiomIcon name="info-filled" />
            </AxiomTooltip>
          </AxiomGroup>
        </template>
        <AxiomInputSlider 
          v-model="formState.rerank_score_threshold" 
          :min="0" 
          :max="1"
          :step="0.01"
        />
      </AxiomFormItem>

      <AxiomFormItem label="重排模型 (postprocessor_profiles)" prop="postprocessor">
        <AxiomSelect
          v-model="selectedReranker"
          placeholder="选择一个重排模型"
          :options="rerankerOptions"
          clearable
          block
        />
      </AxiomFormItem>

      <AxiomFormItem v-if="selectedReranker" label="重排 Top N" prop="reranker_top_n">
        <AxiomInputSlider v-model="rerankerTopN" :min="1" :max="50" />
      </AxiomFormItem>
    </AxiomForm>
    <SavePresetDialog
      :visible="savePresetDialogVisible"
      @update:visible="savePresetDialogVisible = $event"
      @confirm="handleSavePreset"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, inject } from 'vue';
import {
  AxiomForm, AxiomFormItem, AxiomSelect, AxiomInputNumber,
  AxiomRadioGroup, AxiomTitle, AxiomDivider, AxiomIcon, AxiomGroup, AxiomTooltip,
  AxiomInputNumberRange, AxiomInputSlider, AxiomButton
} from 'axiom-view';
import { knowledgeBaseApi } from '@/api/knowledge/knowledgeBase';
import { knowledgeSearchApi } from '@/api/knowledge/knowledgeSearch';
import { presetApi } from '@/api/knowledge/preset';
import SavePresetDialog from './SavePresetDialog.vue';


// --- Data State ---
const formRef = ref(null);
const formState = reactive({
  kb_ids: [],
  query_mode: 'default',
  similarity_top_k: 10,
  context_window: 0,
  rerank_score_threshold: 0.5,
  postprocessor_profiles: null,
});

const knowledgeBases = ref([]);
const rerankerProfiles = ref([]);
const presetStrategies = ref([]); // 全局策略
const queryPresets = ref([]); // 知识库特定预设

const selectedPresetId = ref(null); // 选中的知识库预设ID
const selectedStrategy = ref(''); // 选中的全局策略名称
const selectedReranker = ref(null);
const rerankerTopN = ref(5);
const savePresetDialogVisible = ref(false);

const { notification, useConfirm } = inject('axiom-utils');

const queryModeOptions = ref([
  { label: '默认', value: 'default' },
  { label: '语义', value: 'semantic' },
  { label: '混合', value: 'hybrid' },
]);

// --- Computed Options for Selects ---
const knowledgeBaseOptions = computed(() => 
  knowledgeBases.value.map(kb => ({ label: kb.name, value: kb.id }))
);

const presetStrategyOptions = computed(() => presetStrategies.value);

const queryPresetOptions = computed(() => 
  queryPresets.value.map(p => ({ label: p.name, value: p.id, is_default: p.is_default }))
);

const selectedPreset = computed(() => {
  if (!selectedPresetId.value) return null;
  return queryPresets.value.find(p => p.id === selectedPresetId.value);
});

const isSetDefaultDisabled = computed(() => {
  if (!selectedPreset.value) return true;
  // 核心修正：将 API 返回的 0 或 1 显式转换为布尔值
  return Boolean(selectedPreset.value.is_default);
});

const rerankerOptions = computed(() =>
  rerankerProfiles.value.map(p => ({ label: p.display_text, value: p.profile_name }))
);

// --- API Calls ---
async function fetchInitialData() {
  try {
    const [kbRes, rerankerRes, strategiesRes] = await Promise.all([
      knowledgeBaseApi.listAllSimple(),
      knowledgeSearchApi.getRerankerProfiles(),
      knowledgeSearchApi.getStrategies(),
    ]);
    if (kbRes.success) knowledgeBases.value = kbRes.data;
    if (rerankerRes.success) rerankerProfiles.value = rerankerRes.data;
    if (strategiesRes.success) presetStrategies.value = strategiesRes.data;
  } catch (error) {
    console.error("Failed to fetch initial data for settings panel:", error);
  }
}

async function fetchPresetsForKb() {
  if (formState.kb_ids.length === 0) {
    queryPresets.value = [];
    selectedPresetId.value = null;
    return;
  }
  try {
    const res = await presetApi.getByKbIds(formState.kb_ids);
    if (res && res.success) {
      queryPresets.value = res.data || [];
      const defaultPreset = queryPresets.value.find(p => p.is_default);
      if (defaultPreset) {
        selectedPresetId.value = defaultPreset.id;
        applyKnowledgePreset(defaultPreset.id);
      } else {
        selectedPresetId.value = null;
      }
    }
  } catch (error) {
    console.error("Failed to fetch presets for knowledge bases:", error);
  }
}

// --- Logic ---
function applyKnowledgePreset(presetId) {
  if (!presetId) return;
  
  const preset = queryPresets.value.find(p => p.id === presetId);
  if (preset && preset.config) {
    Object.assign(formState, preset.config);
    
    // 清空全局策略的选择
    selectedStrategy.value = '';

    // 同步重排模型相关状态
    if (formState.postprocessor_profiles) {
      selectedReranker.value = Object.keys(formState.postprocessor_profiles)[0] || null;
      if (selectedReranker.value) {
          rerankerTopN.value = formState.postprocessor_profiles[selectedReranker.value].top_n || 5;
      }
    } else {
      selectedReranker.value = null;
    }
    notification.success({ title: '成功', message: `已应用知识库预设: ${preset.name}`});
  }
}

async function applyGlobalStrategy(strategyName) {
  if (!strategyName) return;

  try {
    const res = await knowledgeSearchApi.getStrategyConfig(strategyName);
    if (res && res.success && res.data) {
      // 核心修正：配置对象在 res.data 内部
      Object.assign(formState, res.data);
      
      // 清空知识库预设的选择
      selectedPresetId.value = null;

      // 同步重排模型相关状态
      if (formState.postprocessor_profiles) {
        selectedReranker.value = Object.keys(formState.postprocessor_profiles)[0] || null;
        if (selectedReranker.value) {
            rerankerTopN.value = formState.postprocessor_profiles[selectedReranker.value].top_n || 5;
        }
      } else {
        selectedReranker.value = null;
      }
      notification.success({ title: '成功', message: `已应用全局策略: ${strategyName}` });
    }
  } catch (error) {
    console.error(`Failed to fetch configuration for strategy: ${strategyName}`, error);
  }
}

async function handleUpdatePreset() {
  if (!selectedPreset.value) return;

  const { kb_ids, ...config } = formState;
  const payload = { config };

  await useConfirm.show({
    title: '确认更新',
    content: `您确定要用当前参数覆盖预设 "${selectedPreset.value.name}" 吗？`,
    type: 'warning',
    onConfirm: async () => {
      const res = await presetApi.update(selectedPresetId.value, payload);
      if (res && res.success) {
        notification.success({ title: '成功', message: '预设更新成功' });
        await fetchPresetsForKb();
      }
    }
  });
}

async function handleSavePreset(name) {
  // 核心修正：根据最新的后端 DTO，config 对象不应包含 kb_ids，因此从 formState 中解构出该字段。
  const { kb_ids, ...config } = formState;

  const payload = {
    name: name,
    kb_ids: kb_ids,
    config: config
  };
  try {
    const res = await presetApi.create(payload);
    if (res && res.success) {
      notification.success({ title: '成功', message: '预设保存成功' });
      await fetchPresetsForKb(); // 刷新列表
      selectedPresetId.value = res.data.id; // 自动选中新创建的
    }
  } catch (error) {
     console.error("Failed to save preset:", error);
  }
}

async function handleSetDefaultPreset() {
  if (isSetDefaultDisabled.value) return;
  const preset = selectedPreset.value;
  if (!preset) return;

  await useConfirm.show({
    title: '确认设置默认',
    content: `您确定要将预设 "${preset.name}" 设置为该知识库组合的默认查询配置吗？`,
    type: 'warning',
    onConfirm: async () => {
      const res = await presetApi.setDefault(selectedPresetId.value);
      if (res && res.success) {
        notification.success({ title: '成功', message: '默认预设设置成功' });
        await fetchPresetsForKb();
      }
    }
  });
}

async function handleDeletePreset() {
  if (!selectedPresetId.value) return;
  const preset = selectedPreset.value;
  if (!preset) return;

  await useConfirm.show({
    title: '确认删除',
    content: `您确定要删除知识库预设 "${preset.name}" 吗？此操作不可撤销。`,
    type: 'error',
    onConfirm: async () => {
      const res = await presetApi.delete(selectedPresetId.value);
      if (res && res.success) {
        notification.success({ title: '成功', message: '预设删除成功' });
        await fetchPresetsForKb();
      }
    }
  });
}

// 监听选择的重排器和 top_n 的变化，自动同步 formState
watch([selectedReranker, rerankerTopN], ([newReranker, newTopN]) => {
  if (newReranker) {
    // 使用新的 top_n 值来构建对象
    formState.postprocessor_profiles = { [newReranker]: { top_n: newTopN } };
  } else {
    formState.postprocessor_profiles = null;
  }
}, { deep: true });

// 监听知识库选择变化，获取对应预设
watch(() => formState.kb_ids, (newVal, oldVal) => {
  // Use deep watch for arrays, or stringify to compare
  if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
    fetchPresetsForKb();
  }
}, { deep: true });

// --- Lifecycle ---
onMounted(fetchInitialData);

// --- Expose to Parent ---
defineExpose({
  getSettings: () => {
    // Return a clean copy of the current settings
    // 移除不属于后端的字段
    const cleanState = { ...formState };
    return JSON.parse(JSON.stringify(cleanState));
  }
});
</script> 